package cn.schoolwow.quickdao.module.database.ddl.query.flow.property.getProperty;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickdao.module.database.parent.domain.ResultSetConsumer;
import cn.schoolwow.quickdao.module.database.parent.flow.executor.ExecuteQueryConnectionFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.sql.ResultSet;
import java.util.Arrays;

public class GetPropertyByH2Flow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        String tableName = (String) flowContext.checkData("tableName");
        String columnName = (String) flowContext.checkData("columnName");

        flowContext.startFlow(new ExecuteQueryConnectionFlow())
                .putTemporaryData("name", "获取指定表指定字段信息")
                .putTemporaryData("sql", "select type_name, is_nullable, column_default from information_schema.`columns` where table_schema = '"+quickDAOConfig.databaseContext.databaseName+"' and table_name = ? and column_name = ?;")
                .putTemporaryData("parameters", Arrays.asList(tableName, columnName))
                .putReturnData("resultSetConsumer",new ResultSetConsumer() {
                    @Override
                    public void consumeResultSet(ResultSet resultSet) throws Exception {
                        if(resultSet.next()){
                            Property property = new Property();
                            property.column = resultSet.getString("column_name");
                            //无符号填充0 => float unsigned zerofill
                            property.columnType = resultSet.getString("type_name");
                            if (property.columnType.contains(" ")) {
                                property.columnType = property.columnType.substring(0, property.columnType.indexOf(" "));
                            }
                            property.notNull = "NO".equals(resultSet.getString("is_nullable"));
                            if (null != resultSet.getString("column_default")) {
                                property.defaultValue = resultSet.getString("column_default");
                            }
                            flowContext.putData("property", property);
                        }
                    }
                })
                .execute();
    }

    @Override
    public String name() {
        return "获取数据库字段-H2数据库";
    }
}
